package store.swing;

import au.com.bytecode.opencsv.CSVReader;
import org.apache.log4j.Logger;
import store.domain.Product;
import store.swing.product.ProductTable;
import store.swing.product.ProductTableModel;
import store.util.AppUtils;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

public class MenuPanel extends JPanel {
    private static final Logger LOGGER = Logger.getLogger(MenuPanel.class);

    private JButton productsButton;
    private JButton ordersButton;
    private JButton productsImportButton;
    private JButton productsExportButton;

    public MenuPanel() {
        initComponents();
    }

    private void initComponents() {
        setLayout(new GridLayout(4, 0, 5, 5));

        productsButton = new JButton("Товары");
        productsButton.addActionListener(new ProductsButtonListener());
        add(productsButton);

        ordersButton = new JButton("Заказы");
        ordersButton.addActionListener(new OrdersButtonListener());
        add(ordersButton);

        productsImportButton = new JButton("Импорт из файла");
        productsImportButton.addActionListener(new ProductsImportButtonListener());
        add(productsImportButton);

        productsExportButton = new JButton("Экспорт в файл");
        productsExportButton.setVisible(false);
        add(productsExportButton);
    }

    //    ======= Listeners =======
    private class ProductsButtonListener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            Component productPanel = getParent().getComponent(0);
            Component orderPanel = getParent().getComponent(1);
            productPanel.setVisible(true);
            orderPanel.setVisible(false);
        }
    }

    private class OrdersButtonListener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            Component productPanel = getParent().getComponent(0);
            Component orderPanel = getParent().getComponent(1);
            productPanel.setVisible(false);
            orderPanel.setVisible(true);
        }
    }

    private class ProductsImportButtonListener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent event) {
            JFileChooser fileChooser = new JFileChooser();
            int ret = fileChooser.showDialog(null, "Выбрать файл");
            if (ret == JFileChooser.APPROVE_OPTION) {
                File selectedFile = fileChooser.getSelectedFile();
                importProductsFromCSV(selectedFile);
                ProductTable.getTableModel().fireTableDataChanged();
                JOptionPane.showMessageDialog(getParent().getComponent(0), "Данные успешно добавленны",
                        "Импорт", JOptionPane.INFORMATION_MESSAGE);
            }
        }

        private void importProductsFromCSV(File selectedFile) {
            List<String[]> stringsList = getEntriesFromCSV(selectedFile);
            List<Product> products = ProductTableModel.getProducts();
            for (String[] strings : stringsList) {
                boolean isExist = false;
                for (Product product : products) {
                    if (product.getProductEan().equals(strings[0])) {
                        product.setProductPrice(Double.valueOf(strings[2]));
                        product.setMinPrice(product.getProductPrice());
                        product.setDateModify(new Timestamp(new Date().getTime()));
                        product.setUnlimited((byte) 0);
                        product.setProductQuantity(Double.valueOf(strings[4]));
                        AppUtils.getService("productService").update(product);
                        isExist = true;
                        break;
                    }
                }
                if (!isExist) {
                    Product newProduct = new Product();
                    newProduct.setProductEan(strings[0]);
                    newProduct.setImage(strings[0] + ".jpg");
                    newProduct.setNameRuRu(strings[1]);
                    newProduct.setProductPrice(Double.valueOf(strings[2]));
                    newProduct.setMinPrice(newProduct.getProductPrice());
                    newProduct.setDescriptionRuRu(strings[3]);
                    newProduct.setProductQuantity(Double.valueOf(strings[4]));
                    AppUtils.getService("productService").create(newProduct);
                }
            }
        }


        private List<String[]> getEntriesFromCSV(File selectedFile) {
            List<String[]> stringsList = null;
            try {
                CSVReader csvReader = new CSVReader(new FileReader(selectedFile.getAbsolutePath()));
                stringsList = csvReader.readAll();
            } catch (FileNotFoundException e) {
                LOGGER.error("File " + selectedFile.getName() + " not found");
            } catch (IOException e) {
                LOGGER.error("File " + selectedFile.getName() + " couldn't be parsed");
            }
            return stringsList;
        }
    }
}

